const urls = {
    log: 'http://pms.dtinsure.com/index.php?m=my&f=effort&type=${date}&orderBy=date_desc&recPerPage=200&pageID=1&date=${date}&t=json',
    productList: 'http://pms.dtinsure.com/?m=product&f=all&productID=0&line=0&status=noclosed&orderBy=order_desc&recTotal=0&recPerPage=10&pageID=1&t=json',
    projectList: 'http://pms.dtinsure.com/?m=project&f=all&status=undone&projectID=0&orderBy=order_desc&productID=0&recTotal=0&recPerPage=10&pageID=1&t=json'
}
const types = {
    'task': '任务',
    'bug': 'BUG',
}
const reg = /pagerMyEffort=\d+;/g;
// $(function () {
let request = (url, type = 'get', data = null, headers = {}) => {
    return new Promise((resolve, reject) => {
        $.ajax({
            url,
            type,
            data,
            headers,
            success(data) {
                resolve(JSON.parse(data))
            }
        })
    })
}

function executeDownload(new_list) {
    $.ajax({
        url: 'https://chenjiwei.cn/api/week/report/ext/path',
        type: 'post',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(new_list),
        success: function (res) {
            if (res.code == 0) {
                let arr = res.msg;
                for (let i = 0; i < arr.length; i++) {
                    const iframe = document.createElement("iframe");
                    iframe.style.display = "none";
                    iframe.src = 'https://chenjiwei.cn/ufs/' + arr[i];
                    document.body.appendChild(iframe);
                    setTimeout(() => {
                        iframe.remove();
                    }, 2 * 60 * 1000);
                }
            } else {
                layer.msg(res.msg)
            }
        }
    });
}

class ZentaoApi {
    constructor() {
        this.headers = {
            "Content-Type": " application/x-www-form-urlencoded"
        }
        this.productDict = {}
        this.projectDict = {}
    }

    async preload() {
        await this.getProductList()
        await this.getProjectList()
    }


    async download() {
        let task_list = await this.getTaskList();
        let task_list_new = []
        let non_task_id = []
        for (let i = 0; i < task_list.length; i++) {
            let obj = task_list[i]
            let id = obj.id;
            let products = obj['product'].split(',').filter(v => !!v).map(s => this.productDict[s]).join(",")
            if (obj.objectType != 'task') {
                non_task_id.push(id);
            }
            let consumed = obj.consumed
            let left = obj.left
            if (isNaN(consumed) || isNaN(left)) {
                layer.alert('编号=(' + id + ')消耗或者剩余不能为空');
                return
            }
            task_list_new.push({
                "id": id,
                "date": obj.date,
                "name": $(".user-name").text(),
                "content": obj.work,
                "usedTime": consumed,
                "lastTime": left,
                "task": `${types[obj.objectType]} #${obj.objectID} ${obj.objectTitle}`,
                "product": products,
                "project": this.projectDict[obj.project]
            });
        }

        if (non_task_id.length != 0) {
            layer.msg('编号=' + non_task_id.join(",") + ' 日志未关联在任务下，确认继续生成周报吗？', {
                time: 0
                , btn: ['冲冲冲', '再改改']
                , yes: function (index) {
                    layer.close(index)
                    executeDownload(task_list_new)
                    return
                }, no: function (index) {
                    layer.close(index)
                    return
                }
            });
        } else {
            executeDownload(task_list_new)
        }
    }

    async getTaskList() {
        let temp = urls.log;
        let url = temp.replaceAll("${date}", $(".btn.btn-link.btn-active-text").attr("id"));
        let res = await request(url, 'get', {}, this.headers);
        return JSON.parse(res.data).efforts
    }

    async getProductList() {
        let res = await request(urls.productList, 'get', {}, this.headers)
        this.productDict = JSON.parse(res.data).products
    }

    async getProjectList() {
        let res = await request(urls.projectList, 'get', {}, this.headers)
        this.projectDict = JSON.parse(res.data).projects
    }
}

